﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConfigCreate.Model
{
    internal class MyPropertyInfo
    {
        private PropertyInfo? pinfo = null;
        private IDictionary<string, object>? list = null;

        public MyPropertyInfo(PropertyInfo pinfo)
        {
            this.pinfo = pinfo;
            PropertyType = pinfo.PropertyType;
            Name = pinfo.Name;
            CanWrite = pinfo.CanWrite;
        }

        public MyPropertyInfo(string name, IDictionary<string, object>? list)
        {
            PropertyType = list?[name]?.GetType();
            if (PropertyType == null && list?.ContainsKey($"{name}-Type") == true)
                PropertyType = list?[$"{name}-Type"] as Type;
            Name = name;
            this.list = list;
        }

        public Type? PropertyType { get; }
        public string? Name { get; }
        public bool CanWrite { get; } = true;

        public object? GetValue(object obj)
        {
            if (pinfo != null)
            {
                return pinfo.GetValue(obj);
            }
            else if (list != null)
            {
                if (obj is IDictionary<string, object> tl)
                    return tl[Name];
            }
            return null;
        }

        public void SetValue(object obj, object value)
        {
            if (pinfo != null)
            {
                pinfo.SetValue(obj, value);
            }
            else if (list != null)
            {
                if(obj is IDictionary<string, object> tl)
                    tl[Name] = value;
            }
        }

        public object? NewObject()
        {
            return Activator.CreateInstance(PropertyType);
        }
    }
}
